const axios = require('axios');

(async () => {
  console.log('🔥 创建新的可参与活动...');
  
  try {
    // 1. 登录管理员账户
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'admin@campus.com',
      password: 'admin123'
    });
    
    const authToken = loginResponse.data.token;
    console.log('✅ 管理员登录成功');
    
    const now = new Date();
    
    // 创建多个不同时间段的活动
    const activities = [
      {
        title: '🎯 立即可参与 - NFT勋章体验',
        description: '专为用户测试设计的活动，立即参与并签到可获得NFT勋章！活动正在进行中，随时欢迎参与。',
        location: '线上活动',
        start_time: new Date(now.getTime() - 2 * 60 * 1000).toISOString(), // 2分钟前开始
        end_time: new Date(now.getTime() + 2 * 60 * 60 * 1000).toISOString(), // 2小时后结束
        max_participants: 100,
        category_id: 1,
        requirements: '无特殊要求，立即参与即可获得勋章',
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '🏃‍♂️ 校园跑步挑战',
        description: '健康生活从跑步开始！参与校园跑步挑战，完成签到即可获得运动达人勋章。',
        location: '校园操场',
        start_time: new Date(now.getTime() + 5 * 60 * 1000).toISOString(), // 5分钟后开始
        end_time: new Date(now.getTime() + 3 * 60 * 60 * 1000).toISOString(), // 3小时后结束
        max_participants: 50,
        category_id: 2,
        requirements: '穿着运动服装，携带水杯',
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '📚 学习分享交流会',
        description: '同学们分享学习心得和经验，互相学习进步。参与即可获得学习先锋勋章。',
        location: '图书馆多功能厅',
        start_time: new Date(now.getTime() + 15 * 60 * 1000).toISOString(), // 15分钟后开始
        end_time: new Date(now.getTime() + 4 * 60 * 60 * 1000).toISOString(), // 4小时后结束
        max_participants: 30,
        category_id: 1,
        requirements: '携带学习材料或笔记本',
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '🎵 音乐欣赏沙龙',
        description: '探索不同音乐风格，分享音乐心得。参与活动可获得艺术爱好者勋章。',
        location: '艺术中心',
        start_time: new Date(now.getTime() + 30 * 60 * 1000).toISOString(), // 30分钟后开始
        end_time: new Date(now.getTime() + 5 * 60 * 60 * 1000).toISOString(), // 5小时后结束
        max_participants: 25,
        category_id: 3,
        requirements: '热爱音乐，愿意分享',
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '💻 编程技术分享',
        description: '程序员聚会！分享编程技巧和项目经验，参与可获得技术达人勋章。',
        location: '计算机实验室',
        start_time: new Date(now.getTime() + 60 * 60 * 1000).toISOString(), // 1小时后开始
        end_time: new Date(now.getTime() + 6 * 60 * 60 * 1000).toISOString(), // 6小时后结束
        max_participants: 40,
        category_id: 1,
        requirements: '具备基本编程知识',
        latitude: 39.90420000,
        longitude: 116.40740000
      }
    ];
    
    console.log('\n🎪 创建活动中...');
    const createdActivities = [];
    
    for (let i = 0; i < activities.length; i++) {
      const activity = activities[i];
      
      try {
        const response = await axios.post('http://localhost:3000/api/activities', activity, {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        
        createdActivities.push(response.data.activity);
        console.log(`✅ ${i + 1}. ${activity.title} - ID: ${response.data.activity.id}`);
      } catch (error) {
        console.log(`❌ ${i + 1}. ${activity.title} - 创建失败: ${error.response?.data?.error || error.message}`);
      }
    }
    
    console.log('\n🎉 活动创建完成！');
    console.log(`📊 成功创建 ${createdActivities.length}/${activities.length} 个活动\n`);
    
    // 测试参与第一个活动（立即可参与的）
    if (createdActivities.length > 0) {
      const testActivity = createdActivities[0];
      console.log('🧪 测试参与第一个活动...');
      
      try {
        // 参与活动
        const joinResponse = await axios.post(`http://localhost:3000/api/activities/${testActivity.id}/join`, {}, {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        console.log('✅ 参与成功:', joinResponse.data.message);
        
        // 尝试签到
        console.log('📝 尝试签到...');
        const checkinResponse = await axios.post(`http://localhost:3000/api/activities/${testActivity.id}/checkin`, {
          latitude: 39.90420000,
          longitude: 116.40740000
        }, {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        
        console.log('✅ 签到成功:', checkinResponse.data.message);
        console.log('🎖️ 勋章状态:', checkinResponse.data.badgeMessage);
        
      } catch (error) {
        console.log('❌ 测试失败:', error.response?.data?.error || error.message);
      }
    }
    
    // 显示所有可参与的活动
    console.log('\n📋 当前可参与的活动列表:');
    const activitiesResponse = await axios.get('http://localhost:3000/api/activities?status=available');
    
    activitiesResponse.data.activities.forEach((activity, index) => {
      const startTime = new Date(activity.start_time);
      const endTime = new Date(activity.end_time);
      const now = new Date();
      
      let status = '';
      if (now < startTime) {
        status = '⏳ 即将开始';
      } else if (now >= startTime && now <= endTime) {
        status = '🟢 进行中';
      } else {
        status = '🔴 已结束';
      }
      
      console.log(`${index + 1}. ${activity.title}`);
      console.log(`   状态: ${status} | 参与人数: ${activity.current_participants}/${activity.max_participants}`);
      console.log(`   ID: ${activity.id} | 地点: ${activity.location}`);
      console.log('');
    });
    
    console.log('🎯 使用提示:');
    console.log('- 绿色状态的活动可以立即参与和签到');
    console.log('- 橙色状态的活动可以参与，等待开始时间后签到');
    console.log('- 在前端页面上点击"参与活动"按钮即可加入');
    console.log('- 参与后在活动时间内可以进行签到获得NFT勋章');
    
  } catch (error) {
    console.error('❌ 创建活动过程出错:', error.message);
    if (error.response) {
      console.error('详细错误:', error.response.data);
    }
  }
})(); 